import character_dispatch from "./dipatch.js";
import SaveManager from "../save/SaveManager.js";
import FullPathData from "../../eventbus/FullPathData.js";
import saveManager from "../save/SaveManager.js";

class Action {
    // 初始化角色动作
    init(character) {
        this.character = null
        this.saveManager = new SaveManager(window)

        let id = character.id
        this.character = character_dispatch.get_character_save(id, this.saveManager)

        if (this.character === null) {
            throw new Error("无法找到对应的角色")
        }
        return this
    }

    // 获取对应的资源图片
    getImage(name = 'headimage'){
        return this.character.getImage(name)
    }

    // 获取对应的移动范围
    get_range_cell() {
        // 获取角色当前位置
        let position = this.character.where;
        if (!position) {
            return {
                color: 'greenyellow',
                data: []
            };
        }

        let {col, row} = position;
        let range = this.character.range;
        let result = [];

        // 遍历所有可能的点
        for (let i = -range; i <= range; i++) {
            for (let j = -range; j <= range; j++) {
                // 计算新坐标
                let newX = col + i;
                let newY = row + j;
                // 检查是否在移动范围内（使用曼哈顿距离）
                if (Math.abs(i) + Math.abs(j) <= range) {
                    // 检查是否在地图范围内
                    if(newX === col && newY === row) continue
                    if (newX >= 0 && newX < this.saveManager.mapsize && 
                        newY >= 0 && newY < this.saveManager.mapsize) {
                        result.push([newY, newX]);
                    }
                }
            }
        }

        return {
            color: 'greenyellow',
            data: result,
            type: "character-move",
            instance: this.character
        };
    }

    // 获取角色对应的动作列表
    get_self_action_list(){
        let player = this.saveManager.load_data('play')
        return this.character.getSelfActionList(player)
    }

    // 保存
    save() {
        // 保存角色数据
        console.log("Saving character:", this.character);
        this.saveManager.save_data(`character-${this.character.id}`, this.character);

        // 获取当前地图数据
        let map_data = this.saveManager.load_data('map-data');
        
        // 遍历地图寻找并更新角色
        for (let i = 0; i < this.saveManager.mapsize; i++) {
            for (let j = 0; j < this.saveManager.mapsize; j++) {
                let cell = map_data[i][j];
                if (cell.character && cell.character.id === this.character.id) {
                    // 找到匹配的角色，更新数据
                    map_data[i][j].character = this.character;
                    
                    // 如果角色位置发生变化，需要清除原位置
                    if (this.character.where.row !== i || this.character.where.col !== j) {
                        map_data[i][j] = this.saveManager.null_map();
                        
                        // 在新位置放置角色
                        let newRow = this.character.where.row;
                        let newCol = this.character.where.col;
                        map_data[newRow][newCol] = {
                            ...this.saveManager.null_map(),
                            character: this.character
                        };
                    }
                    
                    // 保存更新后的地图数据
                    this.saveManager.save_data('map-data', map_data);
                    return;
                }
            }
        }
        
        // 如果没找到角色（新角色），直接在其位置添加
        if (this.character.where) {
            let {row, col} = this.character.where;
            if (row >= 0 && row < this.saveManager.mapsize && 
                col >= 0 && col < this.saveManager.mapsize) {
                map_data[row][col] = {
                    ...this.saveManager.null_map(),
                    character: this.character
                };
                this.saveManager.save_data('map-data', map_data);
            }
        }
    }

    // 消耗魔力值
    lose_mp(number){
        if (this.character.mp >= number){
            this.character.mp -= number;
            return true
        }
        return false
    }

    lose_hp(number){
        if (this.character.hp >= number){
            this.character.hp -= number;
            return true
        }
        return false
    }
}

// Action代理，调用Action的方法其实是调用其this.character的方法
const handler = {
    get(target, name) {
        return target[name] || target.character[name]
    }
}

export default new Proxy(new Action(), handler) // 创建一个代理对象
